import * as $API from '@/utils/api'
import $http from '@/utils/request'
import {
  setToken,
  getToken,
  setCookie,
  getCookie,
  setSession,
  getSession,
  setLocal,
  getLocal,
  removeLocal,
} from '@/utils/navigation'
import { ElMessage } from 'element-plus'

const state = {
  userName: getCookie('SSO_AS_UID'),
  userId: '',
  avator: getCookie('avator'),
  orgUnitName: '',
  orgUnitCode: '',
  token: getToken(),
  access: 0,
  hasGetInfo: false,
  sessionTest: getSession('sessionTest'),
  pageAllowList: getLocal('pageAllowList'),
}

const mutations = {
  setPageAllowList(state, list) {
    state.pageAllowList = list
    setLocal('pageAllowList', JSON.stringify(list))
  },
  setAvator(state, avator) {
    state.avator = avator
    setCookie('avator', avator)
  },
  setUserId(state, id) {
    state.userId = id
  },
  setUserName(state, name) {
    state.userName = name
    setCookie('userName', name)
  },
  setOrgUnitName(state, orgUnitName) {
    state.orgUnitName = orgUnitName
  },
  setOrgUnitCode(state, orgUnitCode) {
    state.orgUnitCode = orgUnitCode
  },
  setAccess(state, access) {
    state.access = access
  },
  setToken(state, token) {
    state.token = token
    setToken(token)
  },
  setHasGetInfo(state, status) {
    state.hasGetInfo = status
  },
  set_sessionTest(state, d) {
    state.sessionTest = d
  },
}

const actions = {
  // gaia登陆
  checkGaiaStatus(response) {
    let notOk = (res) => {
      if (res && res.errno) {
        if (res.errno === 101 && res.redirect) {
          // token失效重新登陆
          return location.replace(res.redirect)
        }
        ElMessage.error(res.errmsg)
      } else if (!res) {
        // 什么都不返回的情况
        ElMessage.error('未知错误，请求异常')
      }
    }
    if (response.status >= 200 && response.status < 300) {
      const username = Cookies.get('SSO_AS_UID')
      store.commit('setUserName', username)
      notOk(response.data)
    } else {
      const error = new Error(response.statusText)
      error.response = response
      throw error
    }
    return response.data
  },
  // 登录
  handleLogin({ commit }, { userName, password }) {
    userName = userName.trim()
    return new Promise((resolve, reject) => {
      commit('setToken', 'tokenTest')
      resolve('123')
    })
    // userName = userName.trim()
    // return new Promise((resolve, reject) => {
    //   $http
    //     .get($API.LOGIN, {
    //       userName,
    //       password,
    //     })
    //     .then((res) => {
    //       const data = res.data
    //       commit('setToken', data.token)
    //       resolve()
    //     })
    //     .catch((err) => {
    //       reject(err)
    //     })
    // })
  },
  // 退出登录
  handleLogOut({ state, commit }) {
    return new Promise((resolve, reject) => {
      commit('setToken', '')
      commit('setAccess', 0)
      commit('setAvator', '')
      commit('setUserName', '')
      removeLocal('tagNaveList')
      resolve()
    })
    // return new Promise((resolve, reject) => {
    //   $http
    //     .post($API.LOGOUT, {
    //       token: state.token,
    //     })
    //     .then(() => {
    //       commit('setToken', '')
    //       commit('setAccess', 0)
    //       commit('setAvator', '')
    //       commit('setUserName', '')
    //       removeLocal('tagNaveList')
    //       resolve()
    //     })
    //     .catch((err) => {
    //       reject(err)
    //     })
    // })
  },
  // 获取用户信息
  getUserInfo({ state, commit }) {
    return new Promise((resolve, reject) => {
      let data = {
        userClass: '0',
        orderId: '0',
        crtUserDate: '2018-12-18 10:35:12',
        postionCode: '4340590',
        mntUserDate: '2018-12-18 14:00:25',
        userCode: 'sevenzhang',
        postionId: '1045',
        enabled: '1',
        orgUnitCode: '34860011',
        account: 'zhangchi',
        crtUserId: 'zhangchi',
        orgUnitId: '106846',
        email: 'sevenzhang@prox.com',
        mntUserId: 'admin',
        postionName: '系统管理主管',
        crtUserName: 'tianjun',
        sex: '1',
        employeeId: '89757',
        isAdmin: '1',
        userName: 'admin',
        userId: '2428',
        version: '3',
        mntUserName: 'zhangchi',
        orgUnitViews: '[ ]',
        userType: '1',
        orgUnitName: '定价补贴',
        avator: 'https://pic4.zhimg.com/7be980a0f_xll.jpg',
        access: 1,
      }
      commit('setAvator', data.avator)
      commit('setUserName', data.userName)
      commit('setOrgUnitName', data.orgUnitName)
      commit('setOrgUnitCode', data.orgUnitCode)
      commit('setUserId', data.userId)
      commit('setAccess', data.access)
      commit('setHasGetInfo', true)
      resolve(data)
    })
  },
  getAllowPage({ state, commit }) {
    return new Promise((resolve, reject) => {
      $http
        .get($API.GET_LEGO_USER_INFO)
        .then((res) => {
          try {
            if (
              res.data &&
              res.data.flags &&
              typeof res.data.flags === 'object'
            ) {
              commit('setPageAllowList', res.data.flags)
              resolve(true)
            } else {
              reject('no data')
            }
          } catch (e) {
            reject(e)
          }
        })
        .catch(() => {
          reject(false)
        })
    })
  },
  act_sessionTest({ commit }, d) {
    commit('set_sessionTest', d)
    setSession('sessionTest', d)
  },
}

export default {
  state,
  mutations,
  actions,
}
